package controlmercancias.gui.cliente;

import controlmercancias.remoto.cliente.Cliente;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class DatosSensor extends JDialog {

    private static final long serialVersionUID = 1L;
    private JTable tabla;
    private JButton cerrar;
    private DefaultTableModel defaultTable;

    public DatosSensor(String id, String datos) {
        this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        this.setModalityType(ModalityType.APPLICATION_MODAL);
        this.setTitle("Datos de sensor");
        defaultTable = new DefaultTableModel(new String[]{"Fecha", "Hora", "Latitud", "Longitud", "Valor"}, 0);
        cargarDatos(datos);
        tabla = new JTable(defaultTable) {

            private static final long serialVersionUID = 1L;

            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        tabla.setAutoCreateRowSorter(true);
        tabla.getTableHeader().setReorderingAllowed(false);
        JScrollPane scrollPane = new JScrollPane(tabla, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane.setBorder(BorderFactory.createTitledBorder("Sensor con ID " + id));
        cerrar = new JButton("Cerrar");
        cerrar.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                DatosSensor.this.setEnabled(false);
                DatosSensor.this.dispose();
            }
        });
        setLayout(new BorderLayout());
        add(scrollPane, BorderLayout.CENTER);
        JPanel temp1 = new JPanel();
        temp1.add(cerrar);
        add(temp1, BorderLayout.SOUTH);

        this.setSize(500, 300);
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        this.setIconImage(Cliente.appIcon);
    }

    private void cargarDatos(String datos) {
        String[] filas = datos.replace("�", "º").split("\n");
        for (String s : filas) {
            String[] s2 = s.split(";");
            String[] coord = s2[2].split("-");
            defaultTable.addRow(new String[]{s2[0], s2[1], coord[0], coord[1], s2[3]});
        }
    }
}
